{% extends 'layout.html' %}

{% block title %}天气数据获取 - PCSE作物模型演示平台{% endblock %}

{% block head %}
<style>
    body {
        font-family: Arial, sans-serif;
        margin: 20px;
    }

    h1 {
        color: #333;
    }

    form {
        margin-bottom: 20px;
    }

    .form-group {
        margin-bottom: 15px;
    }

    label {
        display: inline-block;
        width: 200px;
        text-align: left;
        margin-right: 10px;
        font-weight: bold;
    }

    input[type="number"] {
        padding: 8px;
        width: 200px;
        border: 1px solid #ccc;
        border-radius: 4px;
    }

    button {
        padding: 10px 20px;
        background-color: #2e7d32;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
    }

    button:hover {
        background-color: #1b5e20;
    }

    .result-container {
        margin-top: 20px;
        padding: 20px;
        border: 1px solid #ddd;
        border-radius: 8px;
        background-color: #f9f9f9;
    }

    .chart-container {
        margin-top: 20px;
        height: 400px;
    }

    .loading {
        display: none;
        text-align: center;
        padding: 20px;
        font-style: italic;
    }

    .error {
        color: #d32f2f;
        margin-top: 10px;
    }
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
{% endblock %}

{% block content %}
    <h1>天气数据获取</h1>
    
    <div class="control-panel">
        <h2>参数设置</h2>
        <form id="weather-form">
            <div class="form-group">
                <label for="latitude">纬度:</label>
                <input type="number" id="latitude" value="39.9042" step="0.0001" min="-90" max="90" required>
            </div>
            <div class="form-group">
                <label for="longitude">经度:</label>
                <input type="number" id="longitude" value="116.4074" step="0.0001" min="-180" max="180" required>
            </div>
            <div class="form-group">
                <label for="year">年份:</label>
                <input type="number" id="year" value="2023" min="1984" max="2025" required>
            </div>
            <button type="submit">获取天气数据</button>
        </form>
        
        <div class="loading" id="loading">正在获取天气数据，请稍候...</div>
    </div>
    
    <div class="result-container" id="result-container" style="display: none;">
        <h2>天气数据结果</h2>
        <div id="weather-summary" style="margin-bottom: 20px;"></div>
        
        <div class="chart-section">
            <h3>温度变化趋势</h3>
            <div class="chart-container">
                <canvas id="temperature-chart"></canvas>
            </div>
        </div>
        
        <div class="chart-section">
            <h3>降水量变化趋势</h3>
            <div class="chart-container">
                <canvas id="rainfall-chart"></canvas>
            </div>
        </div>
        
        <div class="chart-section">
            <h3>太阳辐射变化趋势</h3>
            <div class="chart-container">
                <canvas id="radiation-chart"></canvas>
            </div>
        </div>
    </div>
    
    <div class="error" id="error-message"></div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('weather-form');
            const loading = document.getElementById('loading');
            const resultContainer = document.getElementById('result-container');
            const weatherSummary = document.getElementById('weather-summary');
            const errorMessage = document.getElementById('error-message');
            
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const latitude = parseFloat(document.getElementById('latitude').value);
                const longitude = parseFloat(document.getElementById('longitude').value);
                const year = parseInt(document.getElementById('year').value);
                
                // 显示加载状态
                loading.style.display = 'block';
                resultContainer.style.display = 'none';
                errorMessage.textContent = '';
                
                // 发送请求到后端获取天气数据
                fetch('/get_weather_data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        latitude: latitude,
                        longitude: longitude,
                        year: year
                    })
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络请求失败');
                    }
                    return response.json();
                })
                .then(data => {
                    loading.style.display = 'none';
                    
                    if (data.error) {
                        errorMessage.textContent = data.error;
                    } else {
                        // 存储天气数据到变量，用于保存功能
                        window.currentWeatherData = data;
                        
                        // 显示天气数据摘要和保存选项
                        weatherSummary.innerHTML = `
                            <p><strong>数据日期范围:</strong> ${data.date_range}</p>
                            <p><strong>数据总量:</strong> ${data.record_count} 条</p>
                            <p><strong>平均温度:</strong> ${data.avg_temp.toFixed(2)}°C</p>
                            <p><strong>平均降水量:</strong> ${data.avg_rain.toFixed(2)} mm</p>
                            <p><strong>平均太阳辐射:</strong> ${data.avg_rad.toFixed(2)} kJ/m²</p>
                            <div class="form-group" style="margin-top: 20px;">
                                <label for="save_filename">保存文件名:</label>
                                <input type="text" id="save_filename" value="weather_${latitude}_${longitude}_${year}.xlsx" style="width: 300px; padding: 8px; border: 1px solid #ccc; border-radius: 4px;">
                                <button id="save-btn" type="button" style="margin-left: 10px;">保存天气数据</button>
                            </div>
                        `;
                        
                        // 为保存按钮添加点击事件
                        document.getElementById('save-btn').addEventListener('click', function() {
                            saveWeatherData(latitude, longitude, year);
                        });
                        
                        // 显示结果容器
                        resultContainer.style.display = 'block';

                        // 创建温度图表
                        if (data.days && data.tmin && data.tmax) {
                            createTemperatureChart(data.days, data.tmin, data.tmax);
                        }

                        // 创建降水量图表
                        if (data.days && data.rainfall) {
                            createRainfallChart(data.days, data.rainfall);
                        }

                        // 创建太阳辐射图表
                        if (data.days && data.radiation) {
                            createRadiationChart(data.days, data.radiation);
                        }
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    errorMessage.textContent = '获取天气数据失败: ' + error.message;
                });
            });
            
            // 创建温度图表
            function createTemperatureChart(days, tmin, tmax) {
                const ctx = document.getElementById('temperature-chart').getContext('2d');
                
                // 销毁旧图表
                if (window.tempChart) {
                    window.tempChart.destroy();
                }
                
                window.tempChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: days,
                        datasets: [
                            {
                                label: '最低温度 (°C)',
                                data: tmin,
                                borderColor: '#4285f4',
                                backgroundColor: 'rgba(66, 133, 244, 0.1)',
                                borderWidth: 2,
                                fill: false,
                                tension: 0.3
                            },
                            {
                                label: '最高温度 (°C)',
                                data: tmax,
                                borderColor: '#ea4335',
                                backgroundColor: 'rgba(234, 67, 53, 0.1)',
                                borderWidth: 2,
                                fill: false,
                                tension: 0.3
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            title: {
                                display: true,
                                text: '日温度变化趋势'
                            },
                            legend: {
                                position: 'top'
                            }
                        },
                        scales: {
                            x: {
                                display: true,
                                title: {
                                    display: true,
                                    text: '日期'
                                },
                                ticks: {
                                    maxTicksLimit: 12 // 限制x轴标签数量，避免拥挤
                                }
                            },
                            y: {
                                display: true,
                                title: {
                                    display: true,
                                    text: '温度 (°C)'
                                }
                            }
                        }
                    }
                });
            }
            
            // 创建降水量图表
            function createRainfallChart(days, rainfall) {
                const ctx = document.getElementById('rainfall-chart').getContext('2d');
                
                // 销毁旧图表
                if (window.rainChart) {
                    window.rainChart.destroy();
                }
                
                window.rainChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: days,
                        datasets: [
                            {
                                label: '降水量 (mm)',
                                data: rainfall,
                                backgroundColor: 'rgba(66, 133, 244, 0.5)',
                                borderColor: '#4285f4',
                                borderWidth: 1
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            title: {
                                display: true,
                                text: '日降水量变化趋势'
                            },
                            legend: {
                                position: 'top'
                            }
                        },
                        scales: {
                            x: {
                                display: true,
                                title: {
                                    display: true,
                                    text: '日期'
                                },
                                ticks: {
                                    maxTicksLimit: 12 // 限制x轴标签数量，避免拥挤
                                }
                            },
                            y: {
                                display: true,
                                title: {
                                    display: true,
                                    text: '降水量 (mm)'
                                },
                                beginAtZero: true
                            }
                        }
                    }
                });
            }
            
            // 保存天气数据
            function saveWeatherData(latitude, longitude, year) {
                // 检查是否有可用的天气数据
                if (!window.currentWeatherData) {
                    alert('没有可用的天气数据，请先获取数据');
                    return;
                }
                
                // 获取文件名
                const filename = document.getElementById('save_filename').value;
                if (!filename) {
                    alert('请输入文件名');
                    return;
                }
                
                // 显示加载状态
                const saveBtn = document.getElementById('save-btn');
                const originalText = saveBtn.textContent;
                saveBtn.textContent = '保存中...';
                saveBtn.disabled = true;
                
                // 发送POST请求保存数据，包含完整的天气数据
                fetch('/save_weather_data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        filename: filename,
                        latitude: latitude,
                        longitude: longitude,
                        year: year,
                        weather_data: window.currentWeatherData
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('天气数据保存成功\n保存路径: ' + data.filepath);
                    } else {
                        alert('保存失败: ' + data.error);
                    }
                })
                .catch(error => {
                    alert('保存失败: ' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    saveBtn.textContent = originalText;
                    saveBtn.disabled = false;
                });
            }
            
            // 创建太阳辐射图表
            function createRadiationChart(days, radiation) {
                const ctx = document.getElementById('radiation-chart').getContext('2d');
                
                // 销毁旧图表
                if (window.radChart) {
                    window.radChart.destroy();
                }
                
                window.radChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: days,
                        datasets: [
                            {
                                label: '太阳辐射 (kJ/m²)',
                                data: radiation,
                                borderColor: '#fbbc05',
                                backgroundColor: 'rgba(251, 188, 5, 0.1)',
                                borderWidth: 2,
                                fill: true,
                                tension: 0.3
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            title: {
                                display: true,
                                text: '日太阳辐射变化趋势'
                            },
                            legend: {
                                position: 'top'
                            }
                        },
                        scales: {
                            x: {
                                display: true,
                                title: {
                                    display: true,
                                    text: '日期'
                                },
                                ticks: {
                                    maxTicksLimit: 12 // 限制x轴标签数量，避免拥挤
                                }
                            },
                            y: {
                                display: true,
                                title: {
                                    display: true,
                                    text: '太阳辐射 (kJ/m²)'
                                },
                                beginAtZero: true
                            }
                        }
                    }
                });
            }
        });
    </script>
{% endblock %}